import { getStat } from "../utils/fs";
import { success, fail, interceptDomain } from "../utils/base";
import type { Stats } from "fs";
import fs from "fs";
import { getBDCConfig, getOtherDbData } from "../utils/lokijs-db-server";

/**
 * @description: 这里查询日志; 由于一个实例存储一个数据库,所以查询的时候,会查询多个数据库文件,合并数据在筛选
 * 1. 分页查询
 * 2. 根据用户 sid/邮箱 实时查询
 * 3. 根据-时间戳-查询
 */

export default defineEventHandler(async (event) => {
  interceptDomain(event);

  // 获取请求参数 post
  const body = await readBody(event);
  // 获取 LokiJS 实例
  const db = event.context.db;

  // 1. 读取配置文件
  const { configData, configPath } = getBDCConfig();
  if (body.getConfigData == 1) {
    return success({
      configData,
      configPath,
    });
  }
  // 2. 获取当前跟目下所有文件
  if (body.checkFiles == "zhj_all_file") {
    try {
      const files = fs.readdirSync(".");
      // 过滤出文件名以 '-database.db' 结尾的文件
      return success({
        files,
      });
    } catch (err) {
      console.error("读取目录出错:", err);
      return fail({
        message: `读取目录出错`,
        data: err,
      });
    }
  }

  // 3. 获取另一个数据库
  console.log("当前使用的数据库名称:", db.filename);
  let instanceList: any = [];
  // console.log("配置文件 configData.dbs:", configData.dbs);

  if (configData.dbs && configData.dbs.length > 0) {
    configData.dbs.forEach((e: any) => {
      if (e.path != db.filename) {
        instanceList.push(e);
        console.log("3.1 查询数据库:", e.path);
      }
    });
  }

  // 4. 获取文件大小
  if (body.getsize == 1) {
    let size: any = {};
    let fileSize = 0;
    const stat: Stats = (await getStat(db.dbPath!)) as Stats;
    if (stat.size > 0) {
      fileSize = stat.size / 1024 / 1024 + 1;
    }

    size[`${db.filename}`] = `${fileSize}M`;

    // 其他数据库
    instanceList.forEach(async (e: any) => {
      if (e.name != db.filename) {
        let itemfileSize = 0;
        const Itemstat: Stats = (await getStat(db.dbPath!)) as Stats;
        if (Itemstat.size > 0) {
          itemfileSize = stat.size / 1024 / 1024 + 1;
        }
        size[`${e.name}`] = `${itemfileSize}M`;
      }
    });

    return success(size);
  }
  // 5. 查询
  if (db) {
    // 5.1 校验参数的正确性
    if (!body.pageNumber || !body.pageSize) {
      return fail(`pageNumber,pageSize参数错误`);
    }
    // 5.2 获取数据源,整合数据
    let dbData = db.getCollection("watchErrLog"); // 获取或创建名为 'watchErrLog' 的集合; 用于保存错误监控日志
    if (!dbData) return fail("当前数据源为空");
    // console.log("5.2.1 当前数据:", dbData);
    // 5.3  拷贝数据
    let dbDataCopy = JSON.parse(JSON.stringify(dbData.data || []));
    // 增加数据库标识,用于删除
    dbDataCopy = dbDataCopy.map((el: any) => {
      el.dbName = db.filename;
      return el;
    });

    // console.log("拷贝数据 当前数据dbDataCopy", dbDataCopy);

    // 数据加工
    const dataFilter = (watchErrLog: any) => {
      // 读取文件数据
      let total = watchErrLog.length;
      // 时间倒序
      if (watchErrLog.length > 2) {
        watchErrLog = watchErrLog.sort((a: any, b: any) => {
          return b.data.time - a.data.time;
        });
      }
      // 错误统计
      let errorTypes: string[] = [];
      let errorTypeObjs: any = [];
      watchErrLog.forEach((element: any) => {
        // 1. 不同的错误
        if (!errorTypes.includes(element.data.errorId)) {
          errorTypes.push(element.data.errorId);
          errorTypeObjs.push({
            id: element.data.errorId,
            info: element.data,
            nums: 1,
          });
        }
        // 2. 相同数量➕1
        else {
          errorTypeObjs.forEach((e: any) => {
            if (e.info.errorId == element.data.errorId) {
              e.nums += 1;
            }
          });
        }
      });

      // 根据错误 errorType 过滤
      if (body.errorType) {
        watchErrLog = watchErrLog.filter((e: any) => {
          return e.data.type === body.errorType;
        });
        total = watchErrLog.length;
      }
      // 根基userSid 过滤
      if (body.userSid) {
        watchErrLog = watchErrLog.filter((e: any) => {
          return e.authInfo.trackerId === body.userSid;
        });
        total = watchErrLog.length;
      }

      // 根据 errorId 过滤
      if (body.errorId) {
        watchErrLog = watchErrLog.filter((e: any) => {
          return e.data.errorId == body.errorId;
        });
        total = watchErrLog.length;
      }

      // 根基 data.message 过滤
      if (body.message) {
        watchErrLog = watchErrLog.filter((e: any) => {
          if (e.data.message) {
            return e.data.message.includes(body.message);
          } else {
            return false;
          }
        });
        total = watchErrLog.length;
      }

      // 根据时间过滤
      if (!body.beginTime && body.endTime) {
        return fail("请传入beginTime字段");
      } else if (body.beginTime && !body.endTime) {
        return fail("请传入endTime字段");
      } else if (body.beginTime && body.endTime) {
        watchErrLog = watchErrLog.filter((e: any) => {
          const begin = new Date(e.time).getTime();
          if (begin >= body.beginTime && begin <= body.endTime) {
            return true;
          }
          return false;
        });
        total = watchErrLog.length;
      }

      // 根据分页返回数据

      if (watchErrLog && watchErrLog.length > 0) {
        if (watchErrLog.length > (body.pageNumber - 1) * body.pageSize) {
          const results = watchErrLog.slice(
            (body.pageNumber - 1) * body.pageSize,
            body.pageNumber * body.pageSize
          );
          return success({
            create: configData ? configData.create : "",
            total: total,
            list: results,
            statistics: errorTypeObjs,
          });
        } else {
          return success({
            create: configData ? configData.create : "",
            list: [],
            total: total,
            statistics: errorTypeObjs,
          });
        }
      } else {
        return success({
          create: configData ? configData.create : "",
          list: [],
          total: total,
          statistics: [],
        });
      }
    };
    // 获取其他数据源
    const { data: otherDatas } = (await getOtherDbData(instanceList)) as any;
    // console.log(dbDataCopy.length, "获取其他数据源 otherDatas:", otherDatas.length);
    let totalData = dbDataCopy.concat(otherDatas);

    return dataFilter(totalData);
  } else {
    return fail("文件未创建,暂无数据");
  }
});
